import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxr.mom.ci.charging.interworking.entity.InterworkingConfig;
import com.xxr.mom.ci.charging.interworking.vo.api.AccessTokenRequest;
import com.xxr.mom.ci.common.dto.InterworkingParam;
import com.xxr.mom.ci.common.dto.InterworkingResult;
import com.xxr.mom.ci.common.util.EncryptionDecryptionUtil;
import com.xxr.mom.ci.common.util.JsonUtil;

import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Objects;

/**
 * 互联互通客户端测试
 */
public class HlhtClientTtest {

    public static void main(String[] args) throws GeneralSecurityException {
        String method = "query_stations_info";  // 查询站点
//        String method = "query_station_status";   // 查询设备状态
//        String method = "query_station_stats";   // 查询统计信息
//        String method = "query_equip_business_policy";   // 查询业务计费策略
        InterworkingConfig interworkingConfig = getJSONObject("setting", InterworkingConfig.class);
        Object param = getJSONObject(method);
        System.out.println("请求地址：" + interworkingConfig.getOperatorUrl());

        AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
        accessTokenRequest.setOperatorID(interworkingConfig.getOwnerId());
        accessTokenRequest.setOperatorSecret(interworkingConfig.getOwnerSecret());

        JSONObject queryToken = (JSONObject) extracted(interworkingConfig, accessTokenRequest, "query_token", null);
        String accessToken = queryToken.getString("AccessToken");
        extracted(interworkingConfig, param, method, accessToken);
    }

    private static JSON extracted(InterworkingConfig interworkingConfig, Object jsonObject, String method, String token) throws GeneralSecurityException {
        InterworkingParam interworkingParam = getInterworkingParam(interworkingConfig, JsonUtil.toJSONString(jsonObject));
        System.out.println("请求" + method + "参数明文：" + JsonUtil.toJSONString(jsonObject));
        System.out.println("请求" + method + "参数密文：" + JsonUtil.toJSONString(interworkingParam));
        String post = HttpRequest
                .post(interworkingConfig.getOperatorUrl() + method)
                .body(JsonUtil.toJSONString(interworkingParam))
                .header("Authorization", "Bearer " + token)
                .execute()
                .body();
        System.out.println("请求" + method + "结果密文：" + post);
        InterworkingResult postResult = JsonUtil.parseObject(post, InterworkingResult.class);
        if (!Objects.equals(0, postResult.getRet())) {
            throw new RuntimeException(postResult.getMsg());
        }
        String decodeString = EncryptionDecryptionUtil.decode(interworkingConfig.getDecode(), postResult.getData());
        JSON data;
        if (decodeString.startsWith("[")) {
            data = JSON.parseArray(decodeString);
        } else {
            data = JSON.parseObject(decodeString);
        }
        System.out.println("请求" + method + "结果明文：" + data + "\n");
        return data;
    }

    private static Object getJSONObject(String fileName) {
        FileReader fileReader = new FileReader(".\\" + fileName + ".json");
        String str = fileReader.readString();
        if (str.startsWith("[")) {
            return JSON.parseObject(str, JSONArray.class);
        }
        return JSON.parseObject(str, JSONObject.class);
    }

    private static <T> T getJSONObject(String fileName, Class<T> clazz) {
        FileReader fileReader = new FileReader(".\\" + fileName + ".json");
        String str = fileReader.readString();
        return JSON.parseObject(str, clazz);
    }

    private static InterworkingParam getInterworkingParam(InterworkingConfig interworkingConfig, String json) throws GeneralSecurityException {
        InterworkingParam interworkingParam = new InterworkingParam();
        interworkingParam.setOperatorId(interworkingConfig.getOwnerId());
        interworkingParam.setData(EncryptionDecryptionUtil.encrypt(interworkingConfig.getEncrypt(), json));
        interworkingParam.setTimeStamp(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        interworkingParam.setSeq(EncryptionDecryptionUtil.getSeq());
        interworkingParam.setSig(EncryptionDecryptionUtil.sign(interworkingConfig.getOperatorSigSecret(), interworkingParam.getOperatorId() + interworkingParam.getData() + interworkingParam.getTimeStamp() + interworkingParam.getSeq()));
        return interworkingParam;
    }
}
